//
//  TweetDetailViewController.m
//  Guazi
//
//  Created by koolearn on 11-7-29.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "TweetDetailViewController.h"
#import "UserHeaderView.h"
#import "QuartzUtils.h"
#import "NetworkUtil.h"
#import "GuaziAppDelegate.h"
#import "RetweetUsersViewController.h"
#import "RetweetViewController.h"
#import "RemarkInputViewController.h"

@interface TweetDetailViewController (private) 
- (void) showMessagePannel:(NSString*)message;
- (void) hiddenMessagePannel;
@end

@implementation TweetDetailViewController

@synthesize status;


#pragma mark - tool methods

- (void) loadStatus
{
    if ( client ) return;
    client = [[TwitterClient alloc] initWithTarget:self action:@selector(didLoadStatus:obj:)];
    [client loadStatus:status.statusId];
}


- (void) didLoadStatus:(id)sender obj:(NSObject*)obj
{
    client = nil;
    if ( obj == nil ) return;
    if ( ![obj isKindOfClass:[NSDictionary class]] ) return;
    
    NSDictionary* dic = (NSDictionary*) obj;
    Status* s = [Status statusWithJsonDictionary:dic type:TWEET_TYPE_FRIENDS];
    status.forwardCount = s.forwardCount;
    status.remarkCount = s.remarkCount;
    status.originStatus = s.originStatus;
    [Status updateStatus:status.statusId remarkCount:status.remarkCount forwardCount:status.forwardCount];
    [detailView updateStatus:status];
}


#pragma mark - init && destroy methods

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (id) initWithStatus:(Status*)s
{
    self = [super init];
    if ( self ) {
        self.status = s;
    }
    return self;
}


- (UIToolbar*) buildToolbar
{
    UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 376, 320, 40)];
    
    NSMutableArray* items = [NSMutableArray arrayWithCapacity:4];
    
    UIBarButtonItem* forwardItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFastForward target:self action:@selector(retweet)];
    [items addObject:forwardItem];
    [forwardItem release];
    
    UIBarButtonItem* remarkItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(remark)];
    [items addObject:remarkItem];
    [remarkItem release];
    
    UIBarButtonItem* favoriteItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(toggleFavorite)];
    [items addObject:favoriteItem];
    [favoriteItem release];
    
    UIBarButtonItem* refreshItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:nil];
    [items addObject:refreshItem];
    [refreshItem release];
    
	NSMutableArray* arr = [NSMutableArray arrayWithCapacity:2*[items count]-1];
	UIBarButtonItem* item = nil;
	UIBarButtonItem* space = nil;
	
	for ( int i=0; i<[items count]; i++ ) {
        space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                                                               target:self action:nil] autorelease];
        [arr addObject:space];
        
		item = [items objectAtIndex:i];
		[arr addObject:item];
		if ( i == [items count] - 1 ) {
            space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                                                                   target:self action:nil] autorelease];
            [arr addObject:space];
 		}
	}
	
	toolbar.items = arr;
    return [toolbar autorelease];
}


- (void) loadView
{
    UIView* contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    self.view = contentView;
    
    //用户昵称及头像
    CGFloat y = 0;
    CGFloat height = 70;
    UserHeaderView* userview = [[UserHeaderView alloc] initWithUser:status.user];
    userview.frame = CGRectMake(0, y, 320, height);
    [self.view addSubview:userview];
    [userview release];
    y += height;
    
    UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, y, 320, 390-y)];
    
    detailView = [[TweetDetailView alloc] initWithStatus:status];
    detailView.frame = CGRectMake(0, 0, 320, 390-y);
    [scrollView addSubview:detailView];
    
    [self.view addSubview:scrollView];
    [scrollView release];

    
    UIToolbar* toolbar = [self buildToolbar];
    [self.view addSubview:toolbar];
    
    messagePannel = [[MessagePannel alloc] initWithFrame:CGRectMake(0, 376, 320, 40)];
    [messagePannel setHidden:YES];
    [self.view addSubview:messagePannel];
}


- (void)dealloc
{
    [detailView release];
    [messagePannel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void) viewWillAppear:(BOOL)animated
{
    if ( [NetworkUtil isbroadbandAvailable] ) {
        //加载status
        [self loadStatus];
    }
    [super viewWillAppear:YES];
}


- (void)viewDidDisappear:(BOOL)animated
{
    if (client) {
        [client cancel];
        [client release];
        client = nil;
    }
    [super viewDidDisappear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - tool methods

- (void) toggleFavorite:(BOOL)favorited status:(Status*)astatus
{
    [detailView toggleFavorite:favorited status:astatus];
}


- (void) retweet
{
    //RetweetViewController* controller = [[RetweetViewController alloc] initWithStatus:status];
    //UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:controller];
    //[self.navigationController presentModalViewController:nav animated:YES];
    //[controller release];
    //[nav release];
    
    [self showMessagePannel:@"正在转发中..."];
    
    [TwitterClient retweetSync:status];
    [[[GuaziAppDelegate getAppDelegate] currentNavigationController] dismissModalViewControllerAnimated:YES];
    
    status.forwardCount++;
    [detailView.forwardButton setTitle:[NSString stringWithFormat:@"转发(%d)", status.forwardCount] forState:UIControlStateNormal];
    [detailView setNeedsLayout];
    
    [messagePannel stopIndicator];
    [messagePannel setMessage:@"已经成功转发！"];
    [self performSelector:@selector(hiddenMessagePannel) withObject:nil afterDelay:0.8f];
}


- (void) remark
{
    RemarkInputViewController* controller = [[RemarkInputViewController alloc] initWithStatus:status];
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:controller];
    [self.navigationController presentModalViewController:nav animated:YES];
    [controller release];
    [nav release];
}


- (void) toggleFavorite
{
    if ( client ) return;
    
    if ( status.favorited ) {
        [self showMessagePannel:@"取消收藏..."];
    }
    else {
        [self showMessagePannel:@"加为收藏..."];
    }

    client = [[TwitterClient alloc] initWithTarget:self action:@selector(favoriteDidChange:obj:)];
    [client toggleFavorite:status];
}


- (void) favoriteDidChange:(TwitterClient*)sender obj:(NSObject*)obj
{
    client = nil;
    [messagePannel stopIndicator];
    
    NSString* successMessage;
    NSString* failMessage;
    
    if ( status.favorited ) {
        successMessage = @"已经取消了收藏";
        failMessage = @"取消收藏失败";
    }
    else {
        successMessage = @"已经成功加为收藏";
        failMessage = @"加为收藏失败";
    }

    if (sender.hasError) {
        [messagePannel setMessage:failMessage];
    }
    else {
        BOOL favorited = !status.favorited;
        status.favorited = favorited;
        [status updateFavoriteState];
        [messagePannel setMessage:successMessage];
        
        [detailView updateStatus:status];
    }

    [self performSelector:@selector(hiddenMessagePannel) withObject:nil afterDelay:0.8f];
}


- (void)showMessagePannel:(NSString*)message
{
    messagePannel.hidden = NO;
    [messagePannel setMessage:message];
    [messagePannel startIndicator];
}


- (void) hiddenMessagePannel
{
    messagePannel.hidden = YES;
}

@end
